package com.gitee.sparta.common.helpers;

import com.gitee.sparta.common.SpartaConstant;

/**
 * byte[] 工具
 *
 * @author zyred
 * @since v 1.0.0
 */
public class ByteArrayHelper {

    /**
     * int 转 byte[]
     *
     * @param value     目标数字
     * @return          byte arr
     */
    public static byte[] toArray(int value) {
        byte[] result = new byte[SpartaConstant.PROTO_HEAD_LEN];
        // 由高位到低位
        result[0] = (byte) ((value >> 24) & 0xFF);
        result[1] = (byte) ((value >> 16) & 0xFF);
        result[2] = (byte) ((value >> 8) & 0xFF);
        result[3] = (byte) (value & 0xFF);
        return result;
    }

    /**
     * byte[] 转int
     *
     * @param arr   输入的数组
     * @return      int
     */
    public static int toInt(byte[] arr) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < arr.length; i++) {
            int shift = (4 - 1 - i) * 8;
            // 往高位游
            value += (arr[i] & 0x000000FF) << shift;
        }
        return value;
    }

}
